<template>
  <div class="user-list-container">
    <div class="user-list-header">
      <h1>用户列表</h1>
      <div class="header-actions">
        <div class="search-box">
          <input
            v-model="searchUsername"
            type="text"
            placeholder="搜索用户名..."
            class="search-input"
            @keyup.enter="searchUsers"
          />
          <button @click="searchUsers" class="search-btn">搜索</button>
          <button @click="resetSearch" class="reset-btn">重置</button>
        </div>
        <button @click="goBack" class="back-btn">返回</button>
      </div>
    </div>

    <div class="user-list-content">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      <div v-else-if="userList.length === 0" class="empty-users">
        <p>暂无用户</p>
      </div>
      <div v-else class="user-list">
        <div v-for="user in userList" :key="user.id" class="user-card">
          <div class="user-info">
            <div class="user-avatar">
              <span>{{ user.nickname ? user.nickname.charAt(0) : user.username.charAt(0) }}</span>
            </div>
            <div class="user-details">
              <div class="user-name">{{ user.nickname || user.username }}</div>
              <div class="user-meta">
                <span class="username">@{{ user.username }}</span>
                <span v-if="user.email" class="email">{{ user.email }}</span>
                <span v-if="user.phone" class="phone">{{ user.phone }}</span>
              </div>
              <div class="user-status">
                <span :class="['status-badge', user.status === 1 ? 'status-active' : 'status-inactive']">
                  {{ user.status === 1 ? '正常' : '已禁用' }}
                </span>
                <span class="create-time">注册时间：{{ formatTime(user.createTime) }}</span>
              </div>
            </div>
          </div>
          <div class="user-actions">
            <button
              v-if="!isUserBlocked(user.id)"
              @click="handleBlockUser(user)"
              class="block-btn"
              :disabled="blockingUserId === user.id"
            >
              <span v-if="blockingUserId === user.id">拉黑中...</span>
              <span v-else>拉黑</span>
            </button>
            <button
              v-else
              @click="handleUnblockUser(user)"
              class="unblock-btn"
              :disabled="unblockingUserId === user.id"
            >
              <span v-if="unblockingUserId === user.id">取消中...</span>
              <span v-else>取消拉黑</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getUserInfo as getUserInfoFromAuth } from '../utils/auth'
import { searchUsers as searchUsersAPI, blockUser, unblockUser, getBlacklist } from '../api/userInfo'

const router = useRouter()
const currentUser = getUserInfoFromAuth()
const userList = ref([])
const loading = ref(false)
const errorMessage = ref('')
const searchUsername = ref('')
const blockingUserId = ref(null)
const unblockingUserId = ref(null)
const blacklist = ref([])

onMounted(() => {
  loadBlacklist()
  // 默认加载所有用户（搜索空字符串或加载初始数据）
  searchUsers()
})

const loadBlacklist = async () => {
  try {
    const res = await getBlacklist()
    if (res.code === 200) {
      blacklist.value = res.data || []
    }
  } catch (error) {
    console.error('加载黑名单失败:', error)
  }
}

const searchUsers = async () => {
  loading.value = true
  errorMessage.value = ''

  try {
    const res = await searchUsersAPI(searchUsername.value || '')
    if (res.code === 200) {
      // 过滤掉当前用户
      userList.value = (res.data || []).filter(user => user.id !== currentUser?.userId)
    }
  } catch (error) {
    errorMessage.value = error.message || '搜索用户失败'
    console.error('搜索用户失败:', error)
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchUsername.value = ''
  searchUsers()
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const isUserBlocked = (userId) => {
  return blacklist.value.some(item => item.id === userId)
}

const handleBlockUser = async (user) => {
  if (!confirm(`确定要拉黑用户 "${user.nickname || user.username}" 吗？`)) {
    return
  }

  blockingUserId.value = user.id

  try {
    const res = await blockUser(user.id)
    if (res.code === 200) {
      alert('拉黑成功')
      await loadBlacklist()
    }
  } catch (error) {
    alert(error.message || '拉黑失败，请稍后重试')
    console.error('拉黑失败:', error)
  } finally {
    blockingUserId.value = null
  }
}

const handleUnblockUser = async (user) => {
  if (!confirm(`确定要取消拉黑用户 "${user.nickname || user.username}" 吗？`)) {
    return
  }

  unblockingUserId.value = user.id

  try {
    const res = await unblockUser(user.id)
    if (res.code === 200) {
      alert('取消拉黑成功')
      await loadBlacklist()
    }
  } catch (error) {
    alert(error.message || '取消拉黑失败，请稍后重试')
    console.error('取消拉黑失败:', error)
  } finally {
    unblockingUserId.value = null
  }
}

const goBack = () => {
  router.push('/home')
}
</script>

<style scoped>
.user-list-container {
  min-height: 100vh;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-list-header {
  background: white;
  padding: 24px 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.user-list-header h1 {
  color: #333;
  font-size: 28px;
  margin: 0 0 20px 0;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.search-box {
  display: flex;
  gap: 12px;
  align-items: center;
  flex: 1;
}

.search-input {
  flex: 1;
  max-width: 300px;
  padding: 10px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-btn,
.reset-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.search-btn {
  background: #667eea;
  color: white;
}

.search-btn:hover {
  background: #5568d3;
  transform: translateY(-1px);
}

.reset-btn {
  background: #e0e0e0;
  color: #333;
}

.reset-btn:hover {
  background: #d0d0d0;
}

.back-btn {
  padding: 10px 20px;
  background: #e0e0e0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #d0d0d0;
}

.user-list-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.loading,
.error-message {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.error-message {
  color: #f56565;
}

.empty-users {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-users p {
  font-size: 16px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.user-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  transition: all 0.3s;
}

.user-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: 600;
  flex-shrink: 0;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.user-meta {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.username {
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
}

.email,
.phone {
  color: #999;
  font-size: 13px;
}

.user-status {
  display: flex;
  gap: 12px;
  align-items: center;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background: #d4edda;
  color: #155724;
}

.status-inactive {
  background: #f8d7da;
  color: #721c24;
}

.create-time {
  color: #999;
  font-size: 12px;
}

.user-actions {
  display: flex;
  gap: 12px;
}

.block-btn {
  padding: 8px 20px;
  background: #f56565;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.block-btn:hover:not(:disabled) {
  background: #e53e3e;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 101, 101, 0.3);
}

.block-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.unblock-btn {
  padding: 8px 20px;
  background: #e0e0e0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.unblock-btn:hover:not(:disabled) {
  background: #d0d0d0;
}

.unblock-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

